package org.jflame.commons.net.http.handler;

import org.jflame.commons.util.StringHelper;

import java.io.IOException;
import java.net.CookieManager;
import java.net.URI;
import java.util.List;
import java.util.Map;

/**
 * 兼容只有name没有value的非标准cookie(如:HttpOnly,Secure),这类cookie会导致jdk默认CookieManager抛出异常从而导致中断请求
 * 
 * @author charles.zhang
 */
public class LooseCookieManager extends CookieManager {

    final String[] specCookies = { "HttpOnly","Secure" };

    /**
     * 覆盖默认cookie解析,补全不标准的HttpOnly,Secure
     */
    public void put(URI uri, Map<String,List<String>> responseHeaders) throws IOException {
        List<String> tmpLst;
        String[] tmpArr;
        String tmpStr;
        for (String headerKey : responseHeaders.keySet()) {
            if (headerKey == null
                    || !(headerKey.equalsIgnoreCase("Set-Cookie2") || headerKey.equalsIgnoreCase("Set-Cookie"))) {
                continue;
            }
            tmpLst = responseHeaders.get(headerKey);
            // 补全HttpOnly,Secure
            for (int i = 0; i < tmpLst.size(); i++) {
                if (StringHelper.containsAny(tmpLst.get(i), specCookies)) {
                    tmpArr = tmpLst.get(i)
                            .split(";");
                    for (int j = 0; j < tmpArr.length; j++) {
                        if (tmpArr[j].indexOf('=') == -1) {
                            tmpStr = tmpArr[j].trim();
                            if (tmpStr.equalsIgnoreCase(specCookies[0])) {
                                tmpArr[j] = "HttpOnly=true";
                            }
                            if (tmpStr.equalsIgnoreCase(specCookies[1])) {
                                tmpArr[j] = "Secure=true";
                            }
                        }
                    }
                    tmpLst.set(i, String.join(";", tmpArr));
                }
            }
        }
        super.put(uri, responseHeaders);
    }
}
